// pages/news/index.js
import {NewsModel} from '../../model/news'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [{
      img:'/images/a.png'
    }],
    list:[],
    page: 1,
    pagesize: 10,
    noData: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData()
    this.data.type = options.opt
    this.loadData(this.data.type, this.data.page, this.data.pagesize)
  },
  initData(){
    this.setData({
      page: 1,
      list:[],
      pagesize: 10,
      noData: false,
    })
  },
  loadData(type,page,pagesize){
    NewsModel.newsList(type,page,pagesize).then((res) => {
      console.log(res)
      if(res && res.code == 200) {
        this.setData({
          list: this.data.list.concat(res.rows)
        })
        if(this.data.list.length == res.total){
          this.data.noData = true
        }
      }else {
        console.log(res)
      }
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }).catch(e => {
      console.log(e)
      wx.stopPullDownRefresh();
      wx.hideLoading();
    })
  },
  detail(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `./detail/index?id=${id}`,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log('onshow',this.data.page,this.data.pagesize)
    
    // this.data.list = []
    // this.loadData(this.data.type,this.data.page,this.data.pagesize)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.initData()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.initData()
    wx.showLoading({
      title: '玩命加载中',
    })
    wx.stopPullDownRefresh();
    this.loadData(this.data.type,this.data.page, this.data.pagesize)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.noData) return
    console.log('load new')
    this.setData({
      page: this.data.page + 1
    })
    this.loadData(this.data.type,this.data.page, this.data.pagesize)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})